package com.xiong.wuliao;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.xiong.wuliao.entity.TwoStory;
import com.xiong.wuliao.entity.Urls;
import com.xiong.wuliao.util.TwoSpecialJSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 分类页面点击进入后的吐槽小能手和少女Biu的页面
 */
public class TwoSpecialActivity extends AppCompatActivity {
    private TextView myTextViewTwoSpecial; // 标题
    private ImageButton myButtonTwoSpecial; // 返回按钮
    private SwipeRefreshLayout mySwipeRefreshLayoutTwo;
    private ListView myListViewTwo;
    // 自定义适配器
    private MyAdapter adapter;
    // 保存服务器传过来的数据
    private List<TwoStory> twoStories = new ArrayList<>();
    // 刷新后请求服务器的参数
    private int offset = 0;
    // 是否到达页面底部的标注
    private boolean isBottom = false;
    // 是从哪个专题点进来的就去对应的地址
    private String TuOrGirl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two_special);

        findView();
        judgeIntent(); // 判断是从哪个专题点进来的
        initData();  // 初始化数据
        setMyAdapter(); // 设置适配器
        setListener(); // 设置监听
    }

    /**
     * 设置事件监听
     */
    private void setListener() {
        /**
         * 上拉加载的监听
         */
        myListViewTwo.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isBottom && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    offset += 20;
                    getTwoSpecialData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isBottom = firstVisibleItem + visibleItemCount == totalItemCount;
            }
        });

        /**
         * 下拉刷新的监听
         */
        mySwipeRefreshLayoutTwo.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                offset += 20;
                getTwoSpecialData();

            }
        });

        /**
         * ListView的item点击事件
         */
        myListViewTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TwoStory storys = twoStories.get(position);
                String lastId = storys.getId();
                Intent intent = new Intent(TwoSpecialActivity.this, SpecialActivity.class);
                intent.putExtra("lastId", lastId);
                startActivity(intent);
            }
        });

        /**
         * 返回按钮的监听事件
         */
        myButtonTwoSpecial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TwoSpecialActivity.this.finish();
            }
        });
    }

    /**
     * 设置适配器
     */
    private void setMyAdapter() {
        adapter = new MyAdapter(TwoSpecialActivity.this);
        myListViewTwo.setAdapter(adapter);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        getTwoSpecialData();
    }

    /**
     * 判断是从哪个页面点击进来的
     */
    private void judgeIntent() {
        Intent intent = getIntent();
        int intExtra = intent.getIntExtra("TuOrGirl", 0);
        if (intExtra == 0) {
            myTextViewTwoSpecial.setText("吐槽小能手");
            TuOrGirl = Urls.TuSpecialPath;
        } else {
            myTextViewTwoSpecial.setText("少女心BIU");
            TuOrGirl = Urls.NvSpecialPath;
        }
    }

    private void getTwoSpecialData() {
        OkHttpUtils.get(TuOrGirl)
                .params("limit", 20)
                .params("offset", offset)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(s.trim());
                            String result = jsonObject.optString("message");
                            if (result.equals("OK")) {
                                twoStories.addAll(TwoSpecialJSON.saveTwoSpecialData(s.trim()));
                                adapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(TwoSpecialActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 初始化控件
     */
    private void findView() {
        myButtonTwoSpecial = (ImageButton) findViewById(R.id.myButtonTwoSpecial);
        myTextViewTwoSpecial = (TextView) findViewById(R.id.myTextViewTwoSpecial);
        mySwipeRefreshLayoutTwo = (SwipeRefreshLayout) findViewById(R.id.mySwipeRefreshLayoutTwo);
        myListViewTwo = (ListView) findViewById(R.id.myListViewTwo);
    }

    /**
     * ListView的适配器
     */
    private class MyAdapter extends BaseAdapter {
        Context context;
        LayoutInflater inflater;

        public MyAdapter(Context context) {
            this.context = context;
            inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return twoStories.size();
        }

        @Override
        public Object getItem(int position) {
            return twoStories.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TwoStory twoStory = twoStories.get(position);
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.home_adapter_item, null);
                holder = new ViewHolder();
                holder.itemImageView = (ImageView) convertView.findViewById(R.id.itemImageView);
                holder.itemTextView = (TextView) convertView.findViewById(R.id.itemTextView);
                holder.itemImageAgree = (ImageView) convertView.findViewById(R.id.itemImageAgree);
                holder.itemTextViewArgee = (TextView) convertView.findViewById(R.id.itemTextViewArgee);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            Picasso.with(context).load(twoStory.getCover_image_url()).into(holder.itemImageView);
            holder.itemTextView.setText(twoStory.getTitle());
            //boolean isLiked = lists.get(position).get
            // 是否点赞先不做
            holder.itemTextViewArgee.setText(twoStory.getLikes_count());

            return convertView;
        }
    }

    static class ViewHolder {
        public ImageView itemImageView; // 显示List背景的图片
        public TextView itemTextView; // 显示标题的文本
        public ImageView itemImageAgree; // 显示是否点赞的图标
        public TextView itemTextViewArgee; // 显示点赞次数的文字
    }
}
